package com.example.controller;

import com.example.common.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@ResponseBody
@RestController
@RequestMapping("/common")
public class CommonController {//用于文件上传下载
    @Value("${reggie.path}")
    private String BasePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file)//参数的名字要和浏览器里form data里面的name值相同
    {
        //file是上传的临时文件，要转存到其他地方，不然本次请求结束就删除
        log.info(file.getOriginalFilename());

        String originalFilename = file.getOriginalFilename();//原始文件名
        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));//得到后缀
        //通过UUID生成新的文件名
        String fileName= UUID.randomUUID().toString();
        fileName=fileName+suffix;//新的文件名加上后缀
        //创建文件目录
        File dir=new File(BasePath);
        //判断目录是否存在，如果不存在创建新目录
        if(!dir.exists())
        {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(BasePath+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);//返回文件名
    }

    @GetMapping("/download")
    public  void download(String name, HttpServletResponse response)//写入到浏览器：response，从浏览器读：request
    {
        log.info(name);
        //定义输入流读取文件
        try {
            FileInputStream fileInputStream=new FileInputStream(new File(BasePath+name));
            //通过输入流输入到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");//设置回显的是图片文件
            int len=0;
            byte[] bytes=new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1)
            {
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
            //            FileInputStream fileInputStream=new FileInputStream(new File(BasePath+name));
//            ServletOutputStream outputStream = response.getOutputStream();
//            int len=0;
//            byte[] bytes=new byte[1024];
//            while((len=fileInputStream.read(bytes))!=-1)
//            {
//                outputStream.write(bytes,0,len);
//                outputStream.flush();
//            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
